<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>语音识别</title>
</head>
<body>
<button id="startButton">开始</button>
<div id="inputTxt"></div>
</body>
<script>
  var recognition = new webkitSpeechRecognition();
  recognition.lang = "zh-CN";
  recognition.continuous = true;
  recognition.interimResults = true;

  var txt = "";
  var test = "";
  var recognizing = false;
  var finalTranscript = "";
  var start = Date.now();
  var pauseTime = 15000; // 最长停顿时间为15秒
  recognition.onresult = function(event) {
    var result = "";
    for (var i = event.resultIndex; i < event.results.length; i++) {
      if (event.results[i].isFinal) {
        result += event.results[i][0].transcript;
        test +=result;
      } else {
        result += event.results[i][0].transcript;
      }
    }
    var now = Date.now();
    if (now - start >= pauseTime) { // 判断是否超过最长停顿时间
      finalTranscript += test; // 将之前识别的内容添加到最终结果中
      test = ""; // 清空test变量
    }
    start = Date.now();
    txt = result;
    console.log(txt);
    document.getElementById("inputTxt").innerHTML = test;
  };

  recognition.addEventListener("result", (event) => {
    var transcript = event.results[0][0].transcript;
    console.log("识别结果：", transcript);
    finalTranscript = transcript; // 修复第一个bug
  });

  recognition.addEventListener("end", () => {
    console.log("所有的识别结果：", finalTranscript);
    txt = test;
    test = "";
    document.getElementById("inputTxt").innerHTML = txt;
    recognizing = false;
    document.getElementById("startButton").innerHTML = "开始";
    
  });

  document.getElementById("startButton").addEventListener("click", function() {
    if (!recognizing) {
      if (!recognition.running) {
        recognition.start();
      }
      recognizing = true;
      document.getElementById("startButton").innerHTML = "停止";
    } else {
      recognition.stop();
    }
  });
</script>
</html>
